<template>
  <div class="plan-add-information-view">

    <el-form
      ref="ruleForm"
      :inline="true"
      :model="datas"
      :rules="rules"
      class="filter-form-inline"
      label-position="right"
      label-width="120px"
      size="small"
    >
      <el-row>
        <!--                <el-col-->
        <!--                        v-if="datas.chanceId"-->
        <!--                        :span="8"-->
        <!--                >-->
        <!--                    <el-form-item label="关联市场准入：">-->
        <!--                        <span>{{ datas.chanceName }}</span>-->
        <!--                    </el-form-item>-->
        <!--                </el-col>-->

        <el-col :span="8">
          <el-form-item label="关联市场准入">
            <!--            <span>{{ datas.chanceName }}</span>-->

            <!--                        <chance-popover ref="chancePop" @confirm="chanceConfirm">-->

            <!--                            <el-input-->
            <!--                                    v-model="datas.selectName"-->
            <!--                                    placeholder="请输入产品名称"-->
            <!--                                    @blur="chanceBlur"-->
            <!--                                    @focus="chanceFocus"-->
            <!--                            />-->
            <!--                        </chance-popover>-->

            <el-input
              ref="refInput"
              v-model="datas.selectName"
              :disabled="list.length > 0"
              clearable
              @clear="chanceClear"
              placeholder="请输入市场准入"
              @blur="chanceBlur"
              @focus="chanceFocus"
            />

          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            label="规划名称"
            prop="planName"
          >
            <el-input
              v-model="datas.planName"
              clearable
              placeholder="请输入规划名称"
              @blur="nameBlur"
              @input="onInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">

          <el-form-item
            label="规划地区"
            prop="areas"
          >
            <el-cascader
              ref="cascader"
              v-model="datas.areas"
              :disabled="list.length > 0"
              :options="citys"
              :popper-append-to-body="false"
              :props="props1"
              collapse-tags
              placeholder="请选择地区"
              @change="areaChange"
            />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="8">-->
        <!--          <el-form-item-->
        <!--            label="招商模式："-->
        <!--            prop="planMode"-->
        <!--          >-->
        <!--            <el-select-->
        <!--              v-model="datas.planMode"-->
        <!--              placeholder="请选择招商模式"-->
        <!--              :disabled="list.length > 0"-->
        <!--            >-->
        <!--              <el-option-->
        <!--                v-for="item in modelOptions"-->
        <!--                :key="item.value"-->
        <!--                :label="item.label"-->
        <!--                :value="item.value"-->
        <!--              >-->
        <!--              </el-option>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="8">
          <el-form-item
            label="通用名"
            prop="productPopularName"
          >

            <product-popover
              :disabled="disabled || changeChance"
              :searchs="datas.productPopularName"
              type="1"
              @confirm="productConfirm"
            >
              <el-input
                v-model="datas.productPopularName"
                :disabled="datas.chanceId > 0 || list.length > 0"
                placeholder="请输入产品名称"
                @clear="productClear"
                @input="onInput"
              />
            </product-popover>

          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品名">
            <el-input
              v-model="datas.productName"
              disabled
              placeholder="请选择商品名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装规格">
            <el-input
              v-model="datas.packSpecs"
              disabled
              placeholder="请选择包装规格"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产厂家：">
            <el-input
              v-model="datas.producer"
              disabled
              placeholder="请选择生产厂家"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="终端价"
            prop="terminalPrice"
          >
            <app-price-popover
              ref="pricePop"
              :position="datas.chanceId?'bottom-start':'bottom-start'"
              :product-id="datas.productId"
              :props-product="{...datas,...{terminalType:''}}"
              @confirm="priceConfirm"
            >

              <div style="display:flex;justify-content: flex-start">
                <el-select
                  v-model="datas.terminalPrice"
                  placeholder="请选择终端价"
                  @clear="priceClear"
                  @focus="priceFocus"
                >
                  <template #empty />
                </el-select>

                <div
                  v-if="datas.sellUnit"
                  style="margin-left: 10px;min-width: 50px"
                >
                  元/{{ getLabel('sell_unit', datas.sellUnit) }}
                </div>
                <div
                  v-else
                  style="margin-left: 10px"
                >元</div>
              </div>
            </app-price-popover>

            <!--            <price-input-->
            <!--              v-model:data="datas.terminalPrice"-->
            <!--              placeholder="请输入终端价"-->
            <!--              is-unit-->
            <!--              :unit-str="datas.sellUnit ? '元/' + getLabel('sell_unit',datas.sellUnit) : ''"-->
            <!--              :disabled="datas.chanceId > 0"-->
            <!--            />-->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="适用终端"
            prop="terminalType"
          >
            <el-select
              v-model="datas.terminalType"
              :disabled="checkTerminalPrice()"
              placeholder="请选择适用终端"
            >
              <el-option
                v-for="item in appOptions.filter((item) => { return item.value != 'all'})"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="准入模式"
            prop="accessMode"
          >
            <el-select
              v-model="datas.accessMode"
              :disabled="true"
              clearable
              placeholder="请选择准入模式"
            >
              <el-option
                v-for="item in accessOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="价格属性"
            prop="priceProperty"
          >
            <el-select
              v-model="datas.priceProperty"
              :disabled="true"
              clearable
              placeholder="请选择价格属性"
            >
              <el-option
                v-for="item in priceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!--        <el-col :span="8">-->
        <!--          <el-form-item label="指导交易价：">-->
        <!--            <price-input-->
        <!--              v-model:data="datas.guidingPrice"-->
        <!--              placeholder="请输入指导交易价"-->
        <!--              is-unit-->
        <!--              :unit-str="datas.sellUnit ? '元/' + getLabel('sell_unit',datas.sellUnit) : ''"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--                <el-col :span="8">-->
        <!--                    <el-form-item label="招商结束日期：" prop="date">-->
        <!--                        <el-date-picker v-model="datas.date" :disabled-date="disabledDate" type="date" placeholder="请选择结束日期" @change="dateChange"/>-->
        <!--                    </el-form-item>-->
        <!--                </el-col>-->

        <el-col :span="8">
          <el-form-item
            label="规划结束日期"
            prop="date"
          >
            <date-picker
              v-model:date="datas.date"
              :disabled-date="disabledDate"
              placeholder="请选择结束日期"
              @change="dateChange"
            />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <!--
    <el-form
      :model="datas"
      :rules="rules"
      class="filter-form-inline"
      label-position="right"
      label-width="120px"
      size="small"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="其他描述">
            <el-input
              v-model="datas.remark"
              :rows="2"
              placeholder="请输入其他描述"
              type="textarea"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="相关附件">
            <upload-file-view
              :file-arr="datas.files"
              is-upload
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    -->
    <chanceDialog
      ref="chanceDialog"
      type="1"
      @confirm="chanceConfirm"
    />

  </div>
</template>

<script>
import chanceDialog from '../../../modules/chanceDialog'
import { getScreenAreaData } from '../../../../../../../utils/areaFuc'
import area from '../../../../../../../utils/area'
import {
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from 'vue'
import { crmStore } from '@CRM/store'

export default defineComponent({
  name: 'Information',
  components: { chanceDialog },
  props: {
    datas: {
      type: Object,
      default: {},
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: [],
    },
  },
  setup(props, context) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    var cascader = ref(null)
    var pricePop = ref(null)
    var ruleForm = ref(null)
    var chances = ref([])
    var data = reactive({
      chancePop: null,
      citys: area,
      changeChance: false,
      chanceDialog: null,
      refInput: null,
    })
    // const citys = area
    const props1 = reactive({
      multiple: true,
      expandTrigger: 'hover',
      label: 'regionName',
      value: 'regionCode',
    })
    const modelOptions =
      crmStore.getters['dictionary/getDictionary']['plan_mode']

    const priceOptions =
      crmStore.getters['dictionary/getDictionary']['price_type']

    const accessOptions =
      crmStore.getters['dictionary/getDictionary']['access_mode']

    var appOptions = crmStore.getters['dictionary/getDictionary']['app_mode']

    var formData = reactive({
      areas: [],
      model: '',
      no: '',
      product_name: '',
      product_no: '',
      product_x: '',
      app: '',
      price_type: '',
      access: '',
      terminalPrice: '',
      guide_price: '',
      date: '',
      textarea: '',
      files: [],
    })

    // const changevDatas = () => {
    //     context.emit("update:datas", formData);
    // };

    watch(
      () => props.disabled,
      (newval, oldval) => {
        if (!newval) {
          props.datas.areas = currentInstance.proxy.getCascaderAreaData(
            props.datas.region
          )
          if (props.datas.chanceRegion && props.datas.chanceRegion.length) {
            data.citys = getScreenAreaData(props.datas.chanceRegion)
          }
          context.emit('save')
        }
      },
      { immediate: true, deep: true }
    )

    const rules = reactive({
      planName: [
        {
          required: true,
          message: '请输入规划名称',
          trigger: 'blur',
        },
        // {
        //     min: 3,
        //     max: 5,
        //     message: 'Length should be 3 to 5',
        //     trigger: 'blur',
        // },
      ],
      productPopularName: [
        {
          required: true,
          message: '请选择产品',
          trigger: 'blur',
        },
      ],
      areas: [
        {
          required: true,
          message: '请选择地区',
          trigger: 'change',
        },
      ],
      planMode: [
        {
          required: true,
          message: '请选择规划模式',
          trigger: 'change',
        },
      ],
      terminalType: [
        {
          required: true,
          message: '请选择适用终端',
          trigger: 'change',
        },
      ],
      priceProperty: [
        {
          required: true,
          message: '请选择价格属性',
          trigger: 'change',
        },
      ],
      accessMode: [
        {
          required: true,
          message: '请选择准入模式',
          trigger: 'change',
        },
      ],
      terminalPrice: [
        {
          required: true,
          message: '请输入终端价',
          trigger: 'blur',
        },
      ],
      date: [
        {
          type: 'date',
          required: true,
          message: '请选择结束日期',
          trigger: 'change',
        },
      ],
    })

    const onInput = () => {}

    const disabledDate = (time) => {
      return !(time.getTime() > Date.now())
    }

    onMounted(() => {})

    const checkTerminalPrice = () => {
      if (props.datas.chanceId){
        console.log(1111111)
        return true
      }else if (props.list && props.list.length){
        console.log(222222)
        return true
      }else if (!props.datas.isTerminalPrice){
        console.log(3333333)
        return true
      }
      console.log(444444)
      return false
    }

    const chanceBlur = () => {
      if (!props.datas.selectName) {
        props.datas.chanceId = 0
        props.datas.chanceName = ''
        data.citys = area
      }
      if (props.datas.chanceName) {
        props.datas.selectName = props.datas.chanceName
      }
      // data.chancePop.openPopover()
    }

    const chanceFocus = () => {
      // data.chancePop.openPopover()
      data.chanceDialog.openDialog()
      data.refInput.blur()
    }

    const chanceClear = () => {
      data.citys = area
      props.datas.chanceId = 0
      props.datas.chanceName = ''
      props.datas.selectName = ''
      props.datas.chanceRegion = []
    }

    const chanceConfirm = (item) => {
      data.changeChance = true
      props.datas.chanceId = item.id
      props.datas.chanceName = item.chanceName
      props.datas.selectName = item.chanceName
      props.datas.chanceRegion = item.region
      props.datas.region = item.region
      props.datas.region = item.region
      props.datas.accessMode = item.accessMode
      props.datas.terminalType = item.terminalType
      props.datas.expireTime = item.expireTime
      props.datas.priceProperty = item.priceProperty
      props.datas.areas = currentInstance.proxy.getCascaderAreaData(
        props.datas.region
      )
      props.datas.productId = item.productId
      props.datas.productName = item.productName
      props.datas.productPopularName = item.productPopularName
      props.datas.packSpecs = item.packSpecs
      props.datas.approvalNumber = item.approvalNumber
      props.datas.producer = item.producer
      props.datas.sellUnit = item.sellUnit
      data.citys = getScreenAreaData(item.region)

      setTimeout(() => {
        data.changeChance = false
      }, 500)
    }

    const productConfirm = (val) => {
      props.datas.productId = val.id
      props.datas.productPopularName = val.productPopularName
      props.datas.productName = val.productName
      props.datas.approvalNumber = val.approvalNumber
      props.datas.packSpecs = val.packSpecs
      props.datas.producer = val.producer
      props.datas.sellUnit = val.sellUnit
    }

    const productClear = () => {
      props.datas.productId = 0
      props.datas.productPopularName = ''
      props.datas.approvalNumber = ''
      props.datas.packSpecs = ''
      props.datas.sellUnit = ''
    }

    const priceConfirm = (val) => {
      console.log(val)
      props.datas.productPriceId = val.id
      props.datas.app_price = val.terminalPrice
      props.datas.terminalPrice = Number(val.terminalPrice)
      if (!props.datas.chanceId) {
        props.datas.terminalType =
          val.terminalType !== 'all' ? val.terminalType : ''
        props.datas.accessMode = val.accessMode
        props.datas.priceProperty = val.priceType

        if (val.terminalType == 'all'){
          props.datas.isTerminalPrice = true
        }else {
          props.datas.isTerminalPrice = false
        }
      }
    }

    const priceClear = () => {
      props.datas.productPriceId = 0
      props.datas.app_price = ''
      props.datas.terminalPrice = 0
    }

    // var dddd = ref(props.datas)

    const dateChange = (val) => {
      console.log(val.toString())
      if (props.datas.date) {
        props.datas.expireTime = props.datas.date // currentInstance.proxy.dateFormat('yyyy-mm-dd',props.datas.date) + " 23:59:59"
      }
    }

    const areaChange = (val) => {
      console.log(val)

      const serve = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
      props.datas.region = serve
      // console.log("转换服务器地址 ",serve)
      // console.log("转换本地地址 ",currentInstance.proxy.getCascaderAreaData(serve))
    }

    const priceFocus = (val) => {
      if (val) {
        pricePop.value.openPopover()
      } else {
      }
    }

    const nameBlur = () => {
      if (props.datas.planName) {
        const pam = {
          table: 'plan_info',
          column: 'plan_name',
          column_data: props.datas.planName,
          id: props.datas.id ? props.datas.id : 0,
        }
        api.common.COMMON_CHECK_UNIQUE(pam).then((res) => {
          if (!res.code && res.data) {
            if (res.data.exist !== '0') {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: '名称已重复，请重新输入',
              })
            }
          }
        })
      }
    }

    const validate = () => {
      return new Promise((resolve, reject) => {
        ruleForm.value.validate((val) => {
          if (val) {
            resolve()
          } else {
            reject
          }
        })
      })
    }

    return {
      ...toRefs(data),
      ruleForm,
      cascader,
      props1,
      formData,
      rules,
      modelOptions,
      appOptions,
      priceOptions,
      accessOptions,
      pricePop,
      chances,

      onInput,
      productConfirm,
      productClear,
      dateChange,
      priceConfirm,
      priceClear,
      areaChange,
      priceFocus,
      nameBlur,
      validate,
      disabledDate,
      chanceBlur,
      chanceFocus,
      chanceConfirm,
      chanceClear,
      checkTerminalPrice,
    }
  },
})
</script>

<style lang="scss">
.plan-add-information-view {
  .el-form {
    .el-form-item {
      width: 100%;

      .el-form-item__content {
        margin-right: 20px;
      }
    }

    .el-input {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }

    .el-cascader {
      width: 100%;
    }
  }
}
</style>
